import { login, getUserInfo, getUserDetail } from '@/api/user'
const state = {
  token: localStorage.getItem('hr_token2'),
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    localStorage.setItem('hr_token2', data)
    state.token = data
  },
  removeToken(state) {
    localStorage.removeItem('hr_token2')
    state.token = null
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    try {
      const res = await login(data)
      // 调用mutations修改token方法
      store.commit('setToken', res)
      // 在本地中存储一个登录时的时间戳,日期对象.getTime()返回的数值就是时间戳
      // 然后到请求拦截器中处理token值的有效期
      localStorage.setItem('hr_time_key2', (new Date()).getTime())
    } catch (error) {
      console.log(error)
    }
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getUserDetail(res.userId)
    const data = { ...res, ...detail }
    store.commit('setUserInfo', data)
  },
  logout(store) {
    store.commit('removeUserInfo')
    store.commit('removeToken')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
